package com.ctv.my.customview.MaiCustomView.CanvasDraw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.ctv.my.customview.MaiCustomView.CanvasDraw.entity.DrawBean;
import com.ctv.my.customview.MaiCustomView.CanvasDraw.entity.Param;
import com.ctv.my.customview.MaiCustomView.CanvasDraw.utils.DisplayUtil;
import com.ctv.my.customview.MaiCustomView.CanvasDraw.utils.IntersectionUtil;
import com.ctv.my.customview.MaiCustomView.CanvasDraw.utils.SavePicture;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ms on 2017/8/4.
 */

public class DrawView extends View{
    private double touchRadian;//触屏时点的角度
    private double relativeRadian;//相对角度
    private int radius;//半径
    private float pointHexagonY;//六边形上下两角的Y轴绝对值

    private Point firstPoint;
    private Point secondPoint;
    private Point thirdPoint;
    private Point fourthPoint;
    private Point fifthPoint;
    private Point sixthPoint;
    private Point canvasTouchPoint;// 触屏时点击坐标
    private Point defaultPoint = new Point(0, 0);
    private Point intersectionPoint;//长线交点坐标
    private Point intersectionShortPoint;//短线交点坐标

    private Param paramTouch;
    private Param paramHexagon;

    private List<DrawBean> lineList;

    private int state = 1;
    private int stateColor = 4;
    public static final int STATE_DRAW_LONG = 1;
    public static final int STATE_DRAW_SHORT = 2;
    public static final int STATE_ERASE = 3;
    public static final int STATE_DRAW_RED = 4;
    public static final int STATE_DRAW_YELLOW = 5;
    public static final int STATE_DRAW_BLUE = 6;

    /**
     * 获取屏幕的密度
     */
    private final float scale = getContext().getResources().getDisplayMetrics().density;

    /**
     * 字体密度
     */
    private final float fontScale = getContext().getResources().getDisplayMetrics().scaledDensity;
    /**
     * 圆圈控件的画笔
     */
    private Paint circlePaint;

    /**
     * 刻度画笔
     */
    private Paint scalePaint;

    /**
     * 字体画笔
     */
    private Paint textPaint;

    /**
     * 六边形控件画笔
     */
    private Paint hexagonPaint;

    /**
     * 画六边形3条中线的画笔
     */
    private Paint linePaint;

    /**
     * 手指画线的画笔
     */
    private Paint drawLinePaint;

    public DrawView(Context context) {
        super(context);
    }

    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //绘制圆形控件的画笔
        circlePaint = new Paint();
        circlePaint.setAntiAlias(true);//设置抗锯齿
        circlePaint.setColor(Color.argb(99, 105, 105, 105));
        circlePaint.setStrokeWidth(2);//设置笔触大小
        circlePaint.setStyle(Paint.Style.STROKE);//设置填充样式
        //写刻度字画笔
        scalePaint = new Paint();
        scalePaint.setAntiAlias(true);
        scalePaint.setColor(Color.argb(255, 0, 0, 0));
        scalePaint.setStrokeWidth(0.5f);//设置笔触大小
        scalePaint.setTextSize(DisplayUtil.spTopx(fontScale, 10));//设置文字大小
        //绘制六边形的画笔
        hexagonPaint = new Paint();
        hexagonPaint.setAntiAlias(true);//设置抗锯齿
        hexagonPaint.setColor(Color.argb(99, 105, 105, 105));
        hexagonPaint.setStrokeWidth(2);//设置笔触大小
        hexagonPaint.setStyle(Paint.Style.STROKE);
        //字体画笔
        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(Color.argb(255, 0, 0, 0));
        textPaint.setStrokeWidth(0.5f);//设置笔触大小
        textPaint.setTextSize(DisplayUtil.spTopx(fontScale, 14));//设置文字大小
        //三条黑线的画笔
        linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setColor(Color.argb(255, 0, 0, 0));
        linePaint.setStrokeWidth(3);//设置笔触大小
        linePaint.setStyle(Paint.Style.FILL);

        //存储线的列表
        lineList = new ArrayList<DrawBean>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //setMeasuredDimension(DisplayUtil.dipTopx(scale, 320), DisplayUtil.dipTopx(scale, 320));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);
        drawHexagon(canvas);
        //设置线的颜色
        setPaintColor(stateColor);
        //手指画线
        if (intersectionPoint != null && state == STATE_DRAW_LONG) {
            canvas.drawLine(0, 0, intersectionPoint.x, intersectionPoint.y, drawLinePaint);
            intersectionPoint = null;
        }
        if (intersectionPoint != null && state == STATE_DRAW_SHORT) {
            canvas.drawLine(0, 0, intersectionShortPoint.x, intersectionShortPoint.y, drawLinePaint);
            intersectionPoint = null;
        }
        if (lineList != null) {
            for (int i = 0; i < lineList.size(); i++) {
                if (stateColor != STATE_DRAW_BLUE) {
                    if (lineList.get(i).color == 0xFFFF0000) {
                        setPaintColor(STATE_DRAW_RED);
                        canvas.drawLine(0, 0, lineList.get(i).point.x, lineList.get(i).point.y, drawLinePaint);
                    }
                    if (lineList.get(i).color == 0xFFFFFF00) {
                        setPaintColor(STATE_DRAW_YELLOW);
                        canvas.drawLine(0, 0, lineList.get(i).point.x, lineList.get(i).point.y, drawLinePaint);
                    }
                } else {
                    setPaintColor(stateColor);
                    canvas.drawLine(0, 0, lineList.get(i).point.x, lineList.get(i).point.y, drawLinePaint);
                }
            }
        }
    }

    /**
     * 保存为png的方法
     */
    public String savePng() {
        Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        this.draw(canvas);
        String sdcardDir = Environment.getExternalStorageDirectory() + "/canvas/";
        String path = sdcardDir + System.currentTimeMillis() + ".png";
        SavePicture.savePicToSDCard(bitmap, sdcardDir, path);
        return path;
    }

    /**
     * 画底图
     *
     * @param canvas
     */
    private void drawHexagon(Canvas canvas) {

        radius = (getWidth() - 200) / 2;//半径
        int center = getWidth() / 2; //圆心
        canvas.translate(center, center);//把画布平移到背景中间

        double radian60 = Math.PI * 60.0 / 180.0;//60度
        double radian30 = Math.PI * 30.0 / 180.0;//30度
        pointHexagonY = (float) (radius * (Math.sin(radian60)));//六边形的点的Y轴坐标

        //圆形
        canvas.drawCircle(0, 0, radius, circlePaint);

        //六边形
        Path path = new Path();
        firstPoint = new Point(radius, 0);
        path.moveTo(firstPoint.x, firstPoint.y);//第一个点
        canvas.drawText("Ubc", radius + 10, 10, textPaint);

        secondPoint = new Point(radius / 2, (int) -pointHexagonY);
        path.lineTo(secondPoint.x, secondPoint.y);//第二个点
        canvas.drawText("Uac", radius / 2, -(pointHexagonY + 20), textPaint);

        thirdPoint = new Point(-radius / 2, (int) -pointHexagonY);
        path.lineTo(thirdPoint.x, thirdPoint.y);//第三个点
        canvas.drawText("Uab", -((radius / 2) + 50), -(pointHexagonY + 20), textPaint);

        fourthPoint = new Point(-radius, 0);
        path.lineTo(fourthPoint.x, fourthPoint.y);//第四个点
        canvas.drawText("Ucb", -(radius + 70), 10, textPaint);

        fifthPoint = new Point(-(radius / 2), (int) pointHexagonY);
        path.lineTo(fifthPoint.x, fifthPoint.y);//第五个点
        canvas.drawText("Uca", -((radius / 2) + 50), pointHexagonY + 30, textPaint);

        sixthPoint = new Point(radius / 2, (int) pointHexagonY);
        path.lineTo(sixthPoint.x, sixthPoint.y);//第六个点
        canvas.drawText("Uba", radius / 2, pointHexagonY + 30, textPaint);
        path.close();
        canvas.drawPath(path, hexagonPaint);

        //Ub点的坐标
        float pointX = (float) (pointHexagonY * Math.sin(radian60));
        float pointY = (float) (pointHexagonY * Math.sin(radian30));
        //画每条线和线的箭头
        canvas.drawLine(0, 0, 0, -pointHexagonY, linePaint);//中线
        Path pathArrow = new Path();
        pathArrow.moveTo(0, -pointHexagonY);
        pathArrow.lineTo((float) -(15 / (Math.sin(radian60))) / 2, -(pointHexagonY - 15));
        pathArrow.lineTo((float) (15 / (Math.sin(radian60))) / 2, -(pointHexagonY - 15));
        pathArrow.close();
        canvas.drawPath(pathArrow, linePaint);
        canvas.drawText("Ua", -20, -(pointHexagonY + 15), textPaint);

        canvas.drawLine(0, 0, -pointX, pointY, linePaint);//左下角线
        pathArrow.moveTo(-pointX, pointY);
        pathArrow.lineTo((float) -(pointX - 15 / (Math.sin(radian60))), pointY);
        pathArrow.lineTo((float) -(pointX - (15 / (Math.sin(radian60))) / 2), pointY - 15);
        pathArrow.close();
        canvas.drawPath(pathArrow, linePaint);
        canvas.drawText("Uc", -(pointX + 40), pointY + 25, textPaint);

        canvas.drawLine(0, 0, pointX, pointY, linePaint);//右下角线
        pathArrow.moveTo(pointX, pointY);
        pathArrow.lineTo((float) (pointX - 15 / (Math.sin(radian60))), pointY);
        pathArrow.lineTo((float) (pointX - (15 / (Math.sin(radian60))) / 2), pointY - 15);
        pathArrow.close();
        canvas.drawPath(pathArrow, linePaint);
        canvas.drawText("Ub", pointX + 10, pointY + 20, textPaint);
    }

    /**
     * 找出触屏点击的点在哪个区域，并转换成相对角度
     *
     * @param point
     * @return
     */
    private double countRadian(Point point) {
        //切角
        if (point.y == 0 && point.x > 0) {
            relativeRadian = 0;
        } else if (point.x == 0 && point.y < 0) {
            relativeRadian = Math.PI / 2;
        } else if (point.y == 0 && point.x < 0) {
            relativeRadian = Math.PI;
        } else if (point.x == 0 && point.y > 0) {
            relativeRadian = 3 * Math.PI / 2;
        } else {
            touchRadian = Math.atan((double) point.y / (double) point.x);
        }
        //Log.i("真实角度", touchRadian + "");
        //相对角度
        if (touchRadian < 0 && touchRadian >= -Math.PI / 3 && point.x > 0 && point.y < 0) {
            relativeRadian = -touchRadian;
        } else if (touchRadian > -Math.PI / 2 && touchRadian <= -Math.PI / 3 && point.x > 0 && point.y < 0) {
            relativeRadian = -touchRadian;
        } else if (touchRadian > Math.PI / 3 && touchRadian < Math.PI / 2 && point.x < 0 && point.y < 0) {
            relativeRadian = Math.PI - touchRadian;
        } else if (touchRadian > 0 && touchRadian <= Math.PI / 3 && point.x < 0 && point.y < 0) {
            relativeRadian = Math.PI - touchRadian;
        } else if (touchRadian < 0 && touchRadian >= -Math.PI / 3 && point.x < 0 && point.y > 0) {
            relativeRadian = (-touchRadian) + Math.PI;
        } else if (touchRadian > -Math.PI / 2 && touchRadian <= -Math.PI / 3 && point.x < 0 && point.y > 0) {
            relativeRadian = (-touchRadian) + Math.PI;
        } else if (touchRadian > Math.PI / 3 && touchRadian < Math.PI / 2 && point.x > 0 && point.y > 0) {
            relativeRadian = 2 * Math.PI - touchRadian;
        } else if (touchRadian > 0 && touchRadian <= Math.PI / 3 && point.x > 0 && point.y > 0) {
            relativeRadian = 2 * Math.PI - touchRadian;
        }
        return relativeRadian;
    }

    /**
     * 相交点
     *
     * @param radian
     */
    private void countIntersectionPoint(double radian) {
        paramTouch = IntersectionUtil.CalParam(defaultPoint, canvasTouchPoint);
        Log.i("真实角度", canvasTouchPoint + "");
        if (radian >= 0 && radian < Math.PI / 3) {
            paramHexagon = IntersectionUtil.CalParam(firstPoint, secondPoint);
        } else if (radian >= Math.PI / 3 && radian < (Math.PI * 2) / 3) {
            paramHexagon = IntersectionUtil.CalParam(secondPoint, thirdPoint);
        } else if (radian >= (Math.PI * 2) / 3 && radian < Math.PI) {
            paramHexagon = IntersectionUtil.CalParam(thirdPoint, fourthPoint);
        } else if (radian >= Math.PI && radian < (Math.PI * 4) / 3) {
            paramHexagon = IntersectionUtil.CalParam(fourthPoint, fifthPoint);
        } else if (radian >= (Math.PI * 4) / 3 && radian < (Math.PI * 5) / 3) {
            paramHexagon = IntersectionUtil.CalParam(fifthPoint, sixthPoint);
        } else if (radian >= (Math.PI * 5) / 3 && radian < (Math.PI * 2)) {
            paramHexagon = IntersectionUtil.CalParam(sixthPoint, firstPoint);
        }
        intersectionPoint = IntersectionUtil.getIntersectPoint(paramHexagon, paramTouch);
        intersectionShortPoint = new Point(intersectionPoint.x / 2, intersectionPoint.y / 2);
    }

    /**
     * 改变stateColor的值,从而画出不一样颜色的线
     *
     * @param stateColor
     */
    public void setStateColor(int stateColor) {
        if (stateColor == STATE_DRAW_RED || stateColor == STATE_DRAW_YELLOW || stateColor == STATE_DRAW_BLUE) {
            this.stateColor = stateColor;
        }
    }

    /**
     * 改变笔触颜色
     *
     * @param stateColor
     */
    private void setPaintColor(int stateColor) {
        //手指画线的画笔
        drawLinePaint = new Paint();
        drawLinePaint.setAntiAlias(true);
        drawLinePaint.setStrokeWidth(3);
        drawLinePaint.setStyle(Paint.Style.FILL);
        switch (stateColor) {
            case STATE_DRAW_RED:
                drawLinePaint.setColor(Color.RED);//红色
                break;
            case STATE_DRAW_YELLOW:
                drawLinePaint.setColor(Color.YELLOW);//黄色
                break;
            case STATE_DRAW_BLUE:
                //擦除时线的效果
                drawLinePaint.setStrokeWidth(6);
                drawLinePaint.setColor(Color.BLUE);//蓝色
                break;
        }
    }

    /**
     * 改变state的值,从而进行不一样的动作
     *
     * @param state
     */
    public void setState(int state) {
        if (state == STATE_DRAW_LONG || state == STATE_DRAW_SHORT || state == STATE_ERASE) {
            this.state = state;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (state) {
            case STATE_DRAW_LONG:
                handlerDraw(event, state, stateColor);
                break;
            case STATE_DRAW_SHORT:
                handlerDraw(event, state, stateColor);
                break;
            case STATE_ERASE:
                handlerErase(event);
                break;
        }
        return true;
    }

    /**
     * 画线
     *
     * @param event
     */
    private void handlerDraw(MotionEvent event, int state, int stateColor) {
        float touchX = event.getX();
        float touchY = event.getY();
        //触屏点相对圆心的新坐标
        canvasTouchPoint = this.TouchToCanvasPoint(touchX, touchY);
        //先求出相对角度CountRadian(canvasTouchPoint)，再求出在什么区域然后相交的点
        countIntersectionPoint(countRadian(canvasTouchPoint));
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                DrawBean drawBean = new DrawBean();
                switch (state) {
                    case 1:
                        invalidate();
                        drawBean.point = intersectionPoint;
                        drawBean.radian = relativeRadian;
                        switch (stateColor) {
                            case 4:
                                drawBean.color = 0xFFFF0000;//红色
                                break;
                            case 5:
                                drawBean.color = 0xFFFFFF00;//黄色
                                break;
                        }
                        lineList.add(drawBean);
                        break;
                    case 2:
                        invalidate();
                        drawBean.point = intersectionShortPoint;
                        drawBean.radian = relativeRadian;
                        switch (stateColor) {
                            case 4:
                                drawBean.color = 0xFFFF0000;
                                break;
                            case 5:
                                drawBean.color = 0xFFFFFF00;
                                break;
                        }
                        lineList.add(drawBean);
                        break;
                }
                break;
        }
    }

    /**
     * 擦除
     *
     * @param event
     */
    private void handlerErase(MotionEvent event) {
        float touchX = event.getX();
        float touchY = event.getY();
        canvasTouchPoint = this.TouchToCanvasPoint(touchX, touchY);
        double currentRadian = countRadian(canvasTouchPoint);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                setStateColor(4);
                invalidate();
                for (int i = 0; i < lineList.size(); i++) {
                    if (currentRadian < (lineList.get(i).radian + Math.PI / 18) &&
                            currentRadian > (lineList.get(i).radian - Math.PI / 18)
                            ) {
                        setStateColor(6);
                        invalidate();
                        break;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                for (int i = 0; i < lineList.size(); i++) {
                    if (currentRadian < (lineList.get(i).radian + Math.PI / 18) &&
                            currentRadian > (lineList.get(i).radian - Math.PI / 18)
                            ) {
                        lineList.remove(i);
                        setStateColor(4);
                        invalidate();
                        break;
                    }
                }
                break;
        }
    }

    /**
     * 画布平移后的点坐标
     *
     * @param x
     * @param y
     * @return
     */
    private Point TouchToCanvasPoint(float x, float y) {
        int distance = ((getWidth() - 200) / 2) + 100;
        int newX = (int) (x - distance);
        int newY = (int) (y - distance);
        return new Point(newX, newY);
    }
}
